const hre = require("hardhat");
const fs = require("fs");
const path = require("path");

async function main() {
  console.log("Starting deployment...");

  // 获取部署账户
  const [deployer] = await hre.ethers.getSigners();
  console.log("Deploying contracts with account:", deployer.address);

  // 获取账户余额
  const balance = await hre.ethers.provider.getBalance(deployer.address);
  console.log("Account balance:", hre.ethers.formatEther(balance), "ETH");

  // 部署合约
  const CrowdfundingPlatform = await hre.ethers.getContractFactory("CrowdfundingPlatform");
  const crowdfunding = await CrowdfundingPlatform.deploy();

  await crowdfunding.waitForDeployment();

  const contractAddress = await crowdfunding.getAddress();
  console.log("CrowdfundingPlatform deployed to:", contractAddress);

  // 保存部署信息到 JSON 文件
  const deploymentInfo = {
    network: hre.network.name,
    contractAddress: contractAddress,
    deployer: deployer.address,
    deployedAt: new Date().toISOString(),
    chainId: (await hre.ethers.provider.getNetwork()).chainId.toString()
  };

  const deploymentDir = path.join(__dirname, "../deployments");
  if (!fs.existsSync(deploymentDir)) {
    fs.mkdirSync(deploymentDir);
  }

  const deploymentFile = path.join(deploymentDir, `${hre.network.name}.json`);
  fs.writeFileSync(deploymentFile, JSON.stringify(deploymentInfo, null, 2));
  console.log("Deployment info saved to:", deploymentFile);

  // 复制 ABI 到前端项目
  const artifactPath = path.join(__dirname, "../artifacts/contracts/CrowdfundingPlatform.sol/CrowdfundingPlatform.json");
  const frontendContractDir = path.join(__dirname, "../../vue-front/src/contracts");
  
  if (!fs.existsSync(frontendContractDir)) {
    fs.mkdirSync(frontendContractDir, { recursive: true });
  }

  const artifact = JSON.parse(fs.readFileSync(artifactPath, "utf8"));
  const contractInfo = {
    address: contractAddress,
    abi: artifact.abi,
    network: hre.network.name,
    chainId: deploymentInfo.chainId
  };

  fs.writeFileSync(
    path.join(frontendContractDir, "CrowdfundingPlatform.json"),
    JSON.stringify(contractInfo, null, 2)
  );
  console.log("Contract ABI and address copied to frontend");

  console.log("\n=== Deployment Summary ===");
  console.log("Network:", hre.network.name);
  console.log("Contract Address:", contractAddress);
  console.log("Chain ID:", deploymentInfo.chainId);
  console.log("========================\n");
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

